有以下兩點可以區分async和await
async
await
只能用在非同步函數裡面Future<String> createOrderMessage() async {
var order = await fetchUserOrder();
return 'Your order is: $order';
}
Future<String> fetchUserOrder() =>
// Imagine that this function is
// more complex and slow.
Future.delayed(
const Duration(seconds: 2),
() => 'Large Latte',
);
Future<void> main() async {
print('Fetching user order...');
print(await createOrderMessage());
}
Fetching user order...
Your order is: Large Latte
從以上例子我們可以看到async
會在函數的body前宣告,接著宣告async
的函數裡才能用await
,
且 createOrderMessage()回傳的type從String變成Future
在非同步函數body內,第一個await
之前的所有同步code都會立即執行
Future<void> printOrderMessage() async {
print('Awaiting user order...');
var order = await fetchUserOrder();
print('Your order is: $order');
}
Future<String> fetchUserOrder() {
// Imagine that this function is more complex and slow.
return Future.delayed(const Duration(seconds: 4), () => 'Large Latte');
}
void main() async {
countSeconds(4);
await printOrderMessage();
}
// You can ignore this function - it's here to visualize delay time in this example.
void countSeconds(int s) {
for (var i = 1; i <= s; i++) {
Future.delayed(Duration(seconds: i), () => print(i));
}
}
Awaiting user order...
1
2
3
4
Your order is: Large Latte
Future<void> printOrderMessage() async {
var order = await fetchUserOrder();
print('Awaiting user order...');
print('Your order is: $order');
}
1
2
3
4
Awaiting user order...
Your order is: Large Latte
Awaiting user order...會在await做完後才會執行
參考資料:
https://dart.dev/codelabs/async-await